package com.itbac.j2cache.caffeine;

import com.github.benmanes.caffeine.cache.*;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * @description 本地缓存 Caffeine 配置
 *
 * @author itbac
 * @email 1218585258@qq.com
 * @date 2020/6/17
 */
@Configuration
public class CaffeineConfig {
    private static Logger logger = LoggerFactory.getLogger(CaffeineConfig.class);

    //默认过期时间
    private static final int EXPIRE = 3600;

    @Bean(name = "caffeinecache")
    public Cache<String,String> cache() {
        Cache<String, String> cache = Caffeine.newBuilder()
                //缓存最大记录数，超过会被驱逐
                .maximumSize(500)
                //基于时间失效 ,长失效时间用于测试
                .expireAfterAccess(2, TimeUnit.HOURS)
                //移除监听器
                .removalListener(new RemovalListener<String, String>() {
                    @Override
                    public void onRemoval(@Nullable String k, @Nullable String v, RemovalCause removalCause) {
                        logger.info("Caffeine缓存失效，removed key{} cause{}",k,removalCause.toString());
                    }
                })
                //开启统计
                .recordStats()
                .build();
        return cache;
    }


}
